﻿using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace XianboSite.Utility
{
    public sealed class NHibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory sessionFactory;
        private static string configFile = AppDomain.CurrentDomain.BaseDirectory + @"bin\MySql.cfg.xml";

        static NHibernateHelper()
        {
            sessionFactory = new Configuration().Configure(configFile).BuildSessionFactory();
        }

        public static ISession GetCurrentSession()
        {
            ISession currentSession = HttpContext.Current.Application[CurrentSessionKey] as ISession;// Application.Current.Properties[CurrentSessionKey] as ISession;

            if (currentSession == null)
            {
                currentSession = sessionFactory.OpenSession();
                HttpContext.Current.Application[CurrentSessionKey] = currentSession;
                //Application.Current.Properties[CurrentSessionKey] = currentSession;
            }

            return currentSession;
        }

        public static void CloseSession()
        {
            ISession currentSession = HttpContext.Current.Application[CurrentSessionKey] as ISession;// Application.Current.Properties[CurrentSessionKey] as ISession;
            //ISession currentSession = Application.Current.Properties[CurrentSessionKey] as ISession;

            if (currentSession == null)
            {
                // No current session
                return;
            }

            currentSession.Close();
            HttpContext.Current.Application.Remove(CurrentSessionKey);
            //Application.Current.Properties.Remove(CurrentSessionKey);
        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}